#!/usr/bin/env python
# encoding: utf-8
import requests

API = "https://api.appsign.vip:2688"
APPINFO = {
    "version_code": "2.7.0",
    "app_version": "2.7.0",
    "channel": "App%20Stroe",
    "app_name": "aweme",
    "build_number": "27014",
    "aid": "1128",
}

APPINFO = {
    "version_code": "2.8.0",
    "app_version": "2.8.0",
    "channel": "App Stroe",
    "app_name": "aweme",
    "build_number": "28007",
    "aid": "1128",
}

APPINFO = {
    "version_code": "2.9.1",
    "app_version": "2.9.1",
    "channel": "App Stroe",
    "app_name": "aweme",
    "build_number": "29101",
    "aid": "1128",
}

header = {"User-Agent": "Aweme/2.8.0 (iPhone; iOS 11.0; Scale/2.00)"}

# 获取Token       有效期60分钟
def getToken():
    # resp = requests.get(API + "/token/douyin").json()
    resp = requests.get(API + "/token/douyin/version/2.7.0").json()
    token = resp["token"]
    print("Token: " + token)
    return token


# 获取新的设备信息  有效期60分钟永久
def getDevice():
    # resp = requests.get(API + "/douyin/device/new").json()
    resp = requests.get(API + "/douyin/device/new/version/2.7.0").json()
    device_info = resp["data"]
    # device_info = {
    #     "openudid": "befd8d92956cf143eb5dcda11e92cc3f88ddd7d9",
    #     "idfa": "F1F26F8C-B82D-2B8C-EC68-5F0A9712BFEF",
    #     "vid": "76DEE290-2BFD-B57F-F265-FC78D8F3BDAF",
    #     "install_id": 50702090937,
    #     "iid": 50702090937,
    #     "device_id": 59236133998,
    #     "new_user": 1,
    #     "device_type": "iPhone8,1",
    #     "os_version": "11.0",
    #     "os_api": "18",
    #     "screen_width": "750",
    #     "device_platform": "iphone",
    # }
    print("设备信息: " + str(device_info))
    return device_info


# 拼装参数
def params2str(params):
    query = ""
    for k, v in params.items():
        query += "%s=%s&" % (k, v)
    query = query.strip("&")
    print("Sign str: " + query)
    return query


# 使用拼装参数签名
def getSign(token, query):
    if isinstance(query, dict):
        query = params2str(query)
    resp = requests.post(API + "/sign", json={"token": token, "query": query}).json()
    print("签名返回: " + str(resp))
    sign = resp["data"]
    return sign


# 混淆手机号码和密码
def mixString(pwd):
    password = ""
    for i in range(len(pwd)):
        password += hex(ord(pwd[i]) ^ 5)[-2:]
    return password


# 获取短链接的 awemeid
def getAwemeIdByShortUrl(url):
    try:
        return (
            requests.get(url, headers=header, allow_redirects=False)
            .headers["location"]
            .split("/video/")[1]
            .split("/")[0]
        )
    except:
        return ""
